import os
import win32com.client as win32

# Word 到 PDF 转换
def word_to_pdf(word_path, pdf_path):
    word = win32.gencache.EnsureDispatch('Word.Application')
    word.Visible = False
    doc = word.Documents.Open(word_path)
    doc.SaveAs(pdf_path, FileFormat=17)  # 17 表示 PDF 格式
    doc.Close(SaveChanges=False)
    word.Quit()

# 查找电脑上的 .docx 文件
def find_docx_files(directory):
    docx_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.docx'):
                docx_files.append(os.path.join(root, file))
    return docx_files

# 主函数
def main():
    directory = r'D:\软件安装包及其它'  
    docx_files = find_docx_files(directory)
    
    for docx_file in docx_files:
        pdf_file = docx_file.replace('.docx', '.pdf')
        word_to_pdf(docx_file, pdf_file)
        print(f"转换并保存了 {docx_file} 到 {pdf_file}")

if __name__ == "__main__":
    main()